<template>
	<view class="" @click="closepop" :style="{ height: `calc(100vh - ${height + 60}px)` }">
		<scroll-view
			class="message-list-container"
			:style="{ maxHeight: `calc(100vh - ${height + 60}px)` }"
			:scroll-y="true"
			:scroll-top="scrollTop"
			@scrolltoupper="scrolltoupper"
			@scrolltolower="scrolltolower"
			:scroll-into-view="viewscroll"
			@scroll="scroll"
		>
			<view id="message-scroll" style="width: 100%" android:focusable="true">
				<!-- <view class="no-message" style="margin-top: 20rpx" v-if="isCompleted">消息已全部加载</view> -->
				<view v-for="(item, index) in messageList" :key="item.ID" class="t-message" :id="item.ID">
					<view v-if="!item.isRevoked">
						<view class="t-message-item">
							<view v-if="index != 0" class="tim_time">
								<span v-show="item.time - messageList[index + 1].time > 300">
									{{ item.time | dateFormat }}
								</span>
							</view>
							<view class="tim_time" v-show="index == 0">
								{{ item.time | dateFormat }}
							</view>
							<view v-if="item.type !== 'TIMGroupTipElem'" :class="item.flow === 'out' ? 't-self-message' : 't-recieve-message'">
								<image
									class="t-message-avatar"
									mode="aspectFill"
									v-if="item.flow === 'in'"
									:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'"
								></image>
								<view class="">
									<view class="message-main" :class="item.flow === 'out' ? 'message-main-self' : 'message-main-recieve'">
										<view :class="'ites' + index" @longpress="onLongpress(item, index, item.flow === 'out')">
											<TUI-TextMessage v-if="item.type === 'TIMTextElem'" :message="item" :isMine="item.flow === 'out'"></TUI-TextMessage>
											<TUI-ImageMessage v-if="item.type === 'TIMImageElem'" :message="item" :isMine="item.flow === 'out'"></TUI-ImageMessage>
											<TUI-VideoMessage v-if="item.type === 'TIMVideoFileElem'" :message="item" :isMine="item.flow === 'out'"></TUI-VideoMessage>
											<TUI-AudioMessage v-if="item.type === 'TIMSoundElem'" :message="item" :isMine="item.flow === 'out'"></TUI-AudioMessage>
											<TUI-CustomMessage v-if="item.type === 'TIMCustomElem'" :message="item" :isMine="item.flow === 'out'"></TUI-CustomMessage>
										</view>
										<view class="read-receipts" v-if="conversation.type === 'C2C' && item.flow === 'out'">
											<view v-if="item.isPeerRead">已读</view>
											<view v-else>未读</view>
										</view>
									</view>
									<quoteMessage v-if="item.cloudCustomData != ''" :message="item" :isMine="item.flow === 'out'"/>
								</view>
								<image
									class="t-message-avatar avastar_rig"
									mode="aspectFill"
									v-if="item.flow === 'out'"
									:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'"
								></image>
							</view>
						</view>
					</view>
					<view class="tim_time" style="margin: 40rpx auto" v-else>
						<span v-if="item.flow === 'out'">你撤回了一条消息</span>
						<span v-else>对方撤回了一条消息</span>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="message-input" @click.stop="">
			<TUI-message-input id="message-input" ref="messageInput" :conversation="conversation" @sendMessage="sendMessage" />
		</view>
		<MessageOperate @revoke="revokeMessage" @deleteMessage="deleteMessage" @quote="quoteMessage" ref="operateRef"></MessageOperate>
	</view>
</template>

<script>
import TUITextMessage from '../message-elements/text-message/index';
import TUIImageMessage from '../message-elements/image-message/index';
import TUIVideoMessage from '../message-elements/video-message/index';
import TUIAudioMessage from '../message-elements/audio-message/index';
// 自定义消息类型 作为引用消息使用
import TUICustomMessage from '../message-elements/custom-message/index';
import TUIMessageInput from '@/chat/tui-chat/message-input/index';
import MessageOperate from '../message-operate/index.vue';
// 引用消息
import quoteMessage from '../message-elements/quote-message/index.vue';
export default {
	data() {
		return {
			avatar: '',
			userID: '',
			// 当前会话
			messageList: [],
			// 自己的 ID 用于区分历史消息中，哪部分是自己发出的
			nextReqMessageID: '',
			// 下一条消息标志
			isCompleted: false, // 当前会话消息是否已经请求完毕
			scrollTop: 0,
			scrollHeight: 0,
			delmessageList: [],
			isone: true,
			height: uni.getStorageSync('safeAreaInsets').bottom
		};
	},
	components: {
		TUITextMessage,
		TUIImageMessage,
		TUIVideoMessage,
		TUIAudioMessage,
		TUICustomMessage,
		MessageOperate,
		TUIMessageInput,
		quoteMessage
	},
	props: {
		conversation: {
			type: Object,
			default: () => {}
		}
	},
	watch: {
		conversation: {
			handler: function (newVal) {
				if (!newVal.conversationID) return;
				this.setData(
					{
						conversation: newVal
					},
					() => {
						this.getMessageList(newVal);
					}
				);
			},
			immediate: true,
			deep: true
		}
	},
	mounted() {
		uni.$TUIKit.getMyProfile().then((res) => {
			this.avatar = res.data.avatar;
			this.userID = res.data.userID;
		});
		uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
		uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
		uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_REVOKED, this.$onRevokeMessage, this);
	},
	destroyed() {
		// 一定要解除相关的事件绑定
		uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
	},
	methods: {
		// 自己的消息上屏
		sendMessage(event) {
			// 将自己发送的消息写进消息列表里面
			this.messageList = [event.detail.message, ...this.messageList];
			this.scrollToButtom();
		},
		//消息长按
		onLongpress(item, index, isyou) {
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(`.ites${index}`)
					.boundingClientRect((data) => {
						this.$refs.operateRef.open(item, index, data, isyou);
					})
					.exec();
			});
		},
		// 引用消息
		quoteMessage(item) {
			this.$refs.messageInput.quote(item);
		},
		// 删除消息
		deleteMessage(obj) {
			let that = this;
			that.messageList.splice(obj.index, 1);
			that.delmessageList.push(obj.item);
			let promise = uni.$TUIKit.deleteMessage(that.delmessageList);
			promise
				.then(function (imResponse) {
					console.log(imResponse);
					// 删除消息成功
				})
				.catch(function (imError) {
					// 删除消息失败
					console.log('deleteMessage error:', imError);
				});
		},
		// 撤回消息
		revokeMessage(item) {
			console.log(item);
			let promise = uni.$TUIKit.revokeMessage(item);
			promise
				.then(function (imResponse) {
					// 消息撤回成功
				})
				.catch(function (imError) {
					// 消息撤回失败
					console.warn('revokeMessage error:', imError);
				});
		},
		gonewpage() {
			console.log('123');
			uni.navigateTo({
				url: `/pages/chat/newKf/bj?admin_id=${this.conversation.userProfile.userID}`
			});
		},
		closepop() {
			this.$refs.operateRef.close();
			this.$refs.messageInput.closess();
		},
		// 滚动中
		scroll(e) {
			this.$refs.operateRef.close();
		},
		scrolltolower(e) {
			this.isone = false;
			if (this.isCompleted) {
				this.setData({
					isCompleted: true
				});
				return;
			}
			this.getMessageList(this.conversation);
		},
		//页面到达底部，页面翻转后不用此方法
		scrolltoupper(e) {
			console.log('页面到顶部', e);
		},
		getMessageList(conversation) {
			if (!this.isCompleted) {
				uni.$TUIKit
					.getMessageList({
						conversationID: conversation.conversationID,
						nextReqMessageID: this.nextReqMessageID,
						count: 15
					})
					.then((res) => {
						this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
						this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
						let messageList = res.data.messageList.filter((item) => item.isDeleted == false).reverse();
						this.messageList.push(...messageList);
						this.$nextTick(() => {
							if (this.isone) {
								//进入页面滚动到底部
								this.setData({
									scrollTop: 0
								});
							}
						});
					});
			}
		},
		// 消息已读更新
		$onMessageReadByPeer() {
			this.setData({
				messageList: this.messageList
			});
		},
		//消息撤回
		$onRevokeMessage() {
			//撤回后 isRevoked 属性值为 true
			this.setData({
				messageList: this.messageList
			});
		},
		scrollToButtom() {
			const query = uni.createSelectorQuery().in(this);
			let nodesRef = query.select('#message-scroll');
			nodesRef
				.boundingClientRect((res) => {
					this.$nextTick(() => {
						//进入页面滚动到底部
						this.setData({
							scrollTop: res.top
						});
					});
				})
				.exec();
		},
		// 收到的消息
		$onMessageReceived(value) {
			// 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
			const event = value;
			const list = [];
			event.data.forEach((item) => {
				if (item.conversationID === this.conversation.conversationID) {
					list.push(Object.assign(item));
				}
			});
			this.messageList.unshift(...list);
			this.scrollToButtom();
		}
	}
};
</script>
<style lang="scss">
@import './index.css';
</style>